package cn.itrip.auth.controller;

import cn.itrip.auth.service.TokenService;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.MD5;
import cn.itrip.dao.user.ItripUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/api")
@Api
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;
    @Resource
    private ItripUserMapper itripUserMapper;
    /**
     * 使用邮箱注册
     */
    @RequestMapping(value = "/doregister",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public  Dto doregister(@RequestBody  ItripUserVO vo)  {
        //邮箱验证
        if(!this.validEmail(vo.getUserCode())){
            return DtoUtil.returnFail("请输入正确的邮箱", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }
        //调用Service
        ItripUser  user=new ItripUser();
        user.setUserCode(vo.getUserCode());
        user.setUserName(vo.getUserName());
        try {
            if ( userService.findUserByUserCode(user.getUserCode())!=null){
                return DtoUtil.returnFail("用户已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            }else{
                user.setUserPassword(MD5.getMd5(vo.getUserPassword(),32));
                userService.itriptxCreateUser(user);
                return  DtoUtil.returnSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_UNKNOWN);
        }
    }
    /**
     * 使用手机注册
     */
     @RequestMapping(value = "/registerbyphone",method = RequestMethod.POST,produces = "application/json")
     @ResponseBody
    public  Dto doRegisterByPhone(@RequestBody  ItripUserVO vo)  {
         //手机号验证
         if(!this.validPhone(vo.getUserCode())){
            return DtoUtil.returnFail("请输入正确的手机号码", ErrorCode.AUTH_ILLEGAL_USERCODE);
         }
         //调用Service
         ItripUser  user=new ItripUser();
         user.setUserCode(vo.getUserCode());
         user.setUserName(vo.getUserName());
         try {
             if ( userService.findUserByUserCode(user.getUserCode())!=null){
                 return DtoUtil.returnFail("用户已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
             }else{
                 user.setUserPassword(MD5.getMd5(vo.getUserPassword(),32));
                 userService.itriptxCreatUserByPhone(user);
                 return  DtoUtil.returnSuccess();
             }
         } catch (Exception e) {
             e.printStackTrace();
             return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_UNKNOWN);
         }
     }
    /**
     * 使用手机短信验证
     */
    @RequestMapping(value = "/validatephone",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public  Dto validatephone(@RequestParam  String user,@RequestParam  String code)  {
        try {
            if(userService.validatePhone(user,code)){
                 return DtoUtil.returnSuccess("验证成功");
            }else{
                return  DtoUtil.returnSuccess("验证失败");
            }
        } catch (Exception e) {
            return DtoUtil.returnFail("验证失败",ErrorCode.AUTH_UNKNOWN);
        }

    }
    /**
     * 使用邮箱验证
     */
    @RequestMapping(value = "/activate",method = RequestMethod.PUT,produces = "application/json")
    @ResponseBody
    public  Dto activate(@RequestParam  String user,@RequestParam  String code)  {
        try {
            if(userService.activate(user,code)){
                return DtoUtil.returnSuccess("激活成功");
            }else{
                return  DtoUtil.returnSuccess("激活失败");
            }
        } catch (Exception e) {
            return DtoUtil.returnFail("激活失败",ErrorCode.AUTH_UNKNOWN);
        }

    }
    /**
     * 手机验证正则表达式
     * @param phone
     * @return
     */
    private boolean validPhone(String phone){
        String regex="^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }

    /**
     * 邮箱验证正则表达式
     * @param email
     * @return
     */
    private boolean validEmail(String email){
        String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z0-9]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }

    @RequestMapping(value = "/ckusr",method = RequestMethod.GET)
    @ResponseBody
    public Dto checkedUserName(@RequestParam("name") String UserName){
        HashMap map=new HashMap();
        map.put("userName",UserName);
        List list= null;
        try {
           list = itripUserMapper.getItripUserListByMap(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(list.size()==1){
            return  DtoUtil.returnFail("用户名已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
        }else{
            return  DtoUtil.returnDataSuccess("用户名可使用");
        }

    }

@ApiOperation(value = "用户登录")
    @RequestMapping(value = "/dologin",method = RequestMethod.POST)
    @ResponseBody
    public Dto doLogin(@ApiParam(value = "用户名") HttpServletRequest request, @RequestParam("name") String userCode, @RequestParam("password")String UserPassword){
        ItripUser itripUser = null;
        HashMap map = new HashMap();
        map.put("userCode",userCode);
        map.put("userPassword",MD5.getMd5(UserPassword,32));
        try {
            List<ItripUser> list=itripUserMapper.getItripUserListByMap(map);
            itripUser=list.get(0);
            if(list.size()!=1){
                return  DtoUtil.returnFail("密码错误",ErrorCode.AUTH_UNKNOWN);
            }
            String userAgent=request.getHeader("user-agent");
            String token=tokenService.generateToken(userAgent,itripUser);
            tokenService.saveToken(token,itripUser);
            ItripTokenVO vo=new ItripTokenVO(token,Calendar.getInstance().getTimeInMillis()+2*60*60*1000,Calendar.getInstance().getTimeInMillis());
            return  DtoUtil.returnDataSuccess(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return  DtoUtil.returnFail("登录失败",ErrorCode.AUTH_UNKNOWN);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/validateToken",method = RequestMethod.GET,produces = "Application/json",headers = "token")
    public Dto validate(HttpServletRequest request){
        boolean result = tokenService.validate(request.getHeader("user-agent"),request.getHeader("token"));
        if(result){
            return DtoUtil.returnSuccess("Token有效");
        }
        return  DtoUtil.returnFail("Token无效",ErrorCode.AUTH_UNKNOWN);
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET,produces = "Application/json",headers = "token")
    @ResponseBody
    public Dto logout(HttpServletRequest request){
        String token=request.getHeader("token");
        boolean result = tokenService.validate(request.getHeader("user-agent"),token);
        if(result){
            tokenService.delete(token);
            return  DtoUtil.returnSuccess("退出成功");
        }else{
            return  DtoUtil.returnFail("token无效",ErrorCode.AUTH_TOKEN_INVALID);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/retoken",method = RequestMethod.POST,produces = "Application/json",headers = "token")
    public Dto retoken(HttpServletRequest request){
        String token= null;
        try {
            token = tokenService.reloadToken(request.getHeader("user-agent"),request.getHeader("token"));
            ItripTokenVO vo=new ItripTokenVO(token, Calendar.getInstance().getTimeInMillis()+2*60*60*1000,Calendar.getInstance().getTimeInMillis());
            return  DtoUtil.returnDataSuccess(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_REPLACEMENT_FAILED);
        }

    }
}
